#include "frame_producer_consumer.h"
#include <chrono>
#include <thread>
#include <iostream>
#include <iomanip>

// 帧队列实现
bool FrameQueue::enqueue(std::shared_ptr<VideoFrame> frame) {
    if (stopped_) return false;
    
    std::unique_lock<std::mutex> lock(mutex_);
    
    // 等待队列有空间
    cond_.wait(lock, [this]() { 
        return stopped_ || queue_.size() < max_size_; 
    });
    
    if (stopped_) return false;
    
    queue_.push(frame);
    cond_.notify_one();
    return true;
}

bool FrameQueue::dequeue(std::shared_ptr<VideoFrame>& frame, int timeout_ms) {
    std::unique_lock<std::mutex> lock(mutex_);
    
    if (timeout_ms < 0) {
        // 无限等待
        cond_.wait(lock, [this]() { 
            return stopped_ || !queue_.empty(); 
        });
    } else {
        // 超时等待
        auto status = cond_.wait_for(lock, std::chrono::milliseconds(timeout_ms),
            [this]() { return stopped_ || !queue_.empty(); });
        
        if (!status) return false; // 超时
    }
    
    if (stopped_) return false;
    
    frame = queue_.front();
    queue_.pop();
    cond_.notify_one();
    return true;
}

// 帧生产者实现
FrameProducer::FrameProducer(FrameQueue& queue, size_t min_frame_size, size_t max_frame_size)
    : queue_(queue), running_(false), next_frame_id_(1),
      rng_(std::random_device{}()),
      frame_size_dist_(min_frame_size, max_frame_size),
      frame_interval_dist_(30, 40) // 模拟25-33fps (30-40ms间隔)
{}

FrameProducer::~FrameProducer() {
    stop();
}

void FrameProducer::start() {
    running_ = true;
    thread_ = std::thread([this]() {
        while (running_) {
            // 生成随机帧大小
            size_t frame_size = frame_size_dist_(rng_);
            
            // 创建新帧
            auto frame = std::make_shared<VideoFrame>(next_frame_id_++, frame_size);
            
            // 入队
            if (!queue_.enqueue(frame)) {
                std::cerr << "Failed to enqueue frame " << frame->getFrameId() << std::endl;
            }
            
            // 随机间隔，模拟不同的帧率
            int interval_ms = frame_interval_dist_(rng_);
            std::this_thread::sleep_for(std::chrono::milliseconds(interval_ms));
        }
    });
}

void FrameProducer::stop() {
    if (running_) {
        running_ = false;
        if (thread_.joinable()) {
            thread_.join();
        }
    }
}

// 帧消费者实现
FrameConsumer::FrameConsumer(FrameQueue& queue, FrameStatistics& statistics)
    : queue_(queue), statistics_(statistics), running_(false) {
    // 初始化处理管道
    pipeline_.addProcessor(std::make_unique<CaptureProcessor>());
    pipeline_.addProcessor(std::make_unique<EncodeProcessor>());
    pipeline_.addProcessor(std::make_unique<SendProcessor>());
    pipeline_.addProcessor(std::make_unique<ReceiveProcessor>());
    pipeline_.addProcessor(std::make_unique<DecodeProcessor>());
    pipeline_.addProcessor(std::make_unique<RenderProcessor>());
}

FrameConsumer::~FrameConsumer() {
    stop();
}

void FrameConsumer::start() {
    running_ = true;
    thread_ = std::thread([this]() {
        while (running_) {
            std::shared_ptr<VideoFrame> frame;
            if (queue_.dequeue(frame, 100)) { // 100ms超时
                // 处理帧
                auto processed_frame = pipeline_.processFrame(frame);
                
                // 添加到统计
                if (processed_frame) {
                    statistics_.addFrame(processed_frame);
                }
            }
        }
    });
}

void FrameConsumer::stop() {
    if (running_) {
        running_ = false;
        if (thread_.joinable()) {
            thread_.join();
        }
    }
}

// 统计定时器实现
StatisticsTimer::StatisticsTimer(FrameStatistics& statistics, std::chrono::seconds interval)
    : statistics_(statistics), interval_(interval), running_(false) {}

StatisticsTimer::~StatisticsTimer() {
    stop();
}

void StatisticsTimer::start() {
    running_ = true;
    thread_ = std::thread([this]() {
        while (running_) {
            // 等待一个统计周期
            std::this_thread::sleep_for(interval_);
            
            // 计算并重置统计数据
            if (statistics_.hasEnoughData()) {
                auto stats = statistics_.calculateAndReset();
                
                // 打印统计结果
                std::cout << "\n=== 统计周期: " 
                          << std::chrono::duration_cast<std::chrono::seconds>(
                                 stats.window_end - stats.window_start
                             ).count() << "秒 ===" << std::endl;
                
                std::cout << "帧率: " << std::fixed << std::setprecision(2) 
                          << stats.avg_frame_rate << " fps" << std::endl;
                
                std::cout << "码率: " << std::fixed << std::setprecision(2) 
                          << stats.avg_bitrate << " Kbps" << std::endl;
                
                std::cout << "平均帧大小: " << std::fixed << std::setprecision(2) 
                          << stats.avg_frame_size / 1024 << " KB (" 
                          << stats.min_frame_size / 1024 << "-" 
                          << stats.max_frame_size / 1024 << " KB)" << std::endl;
                
                std::cout << "平均帧间隔: " << std::fixed << std::setprecision(2) 
                          << stats.avg_interval << " ms" << std::endl;
                
                std::cout << "端到端延迟: " << std::fixed << std::setprecision(2) 
                          << stats.avg_end_to_end << " ms (min: " 
                          << stats.min_end_to_end << ", max: " 
                          << stats.max_end_to_end << ")" << std::endl;
                
                std::cout << "----------------------------------------" << std::endl;
            } else {
                std::cout << "\n统计周期内无数据..." << std::endl;
            }
        }
    });
}

void StatisticsTimer::stop() {
    if (running_) {
        running_ = false;
        if (thread_.joinable()) {
            thread_.join();
        }
    }
}
